﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using MigSharp;

namespace CmsDatabaseMigrations.Migrations
{    
    public abstract class StoredProcedureMigration : IReversibleMigration
    {
        private readonly Regex split = new Regex(@"(.*?)\s+go",
                                        RegexOptions.Compiled | RegexOptions.Multiline | RegexOptions.IgnoreCase);
        protected abstract string SpFileName { get; }        
        public virtual void Up(IDatabase db)
        {
            foreach (string query in GetQueryFromFile("up", SpFileName))
            {
                db.Execute(query);
            }
        }

        public virtual void Down(IDatabase db)
        {
            foreach (string query in GetQueryFromFile("down", SpFileName))
            {
                db.Execute(query);
            }            
        }

        private IEnumerable<string> GetQueryFromFile(string subFolder, string fileName)
        {
            var pathToFile = Path.Combine(MigrationsConfiguration.PathToStoredProcedures, subFolder);
            pathToFile = Path.Combine(pathToFile, fileName);

            if (!File.Exists(pathToFile))
            {
                throw new ArgumentOutOfRangeException("fileName", "File does not exist");
            }

            string result = File.ReadAllText(pathToFile).Replace("\r\n", " *line_break* ");

            while (split.IsMatch(result))
            {
                yield return split.Match(result).Groups[1].Value.Replace("*line_break*", "\r\n");
                result = split.Replace(result, "", 1, 0);
            }            
        }        
    }
}